package com.example.springbgootjwt.controller;

import cn.hutool.core.io.FileUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Controller
public class UploadFileController {

    private static String UPLOADED_FOLDER = "D://temp//";

    @PostMapping("/upload")
    @ResponseBody
    public String singleFileUpload(@RequestParam("file") MultipartFile file,
                                   RedirectAttributes redirectAttributes) {
        if (file.isEmpty()) {
            return "文件上传失败";
        }

        try {
            byte[] bytes = file.getBytes();
            Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
            if(!FileUtil.exist(UPLOADED_FOLDER)){
                FileUtil.mkdir(UPLOADED_FOLDER);
            }
            Files.write(path, bytes);

            redirectAttributes.addFlashAttribute("message","文件名为" + file.getOriginalFilename() + "的文件上传成功");

        } catch (IOException e) {
            e.printStackTrace();
            return "文件上传失败";
        }

        return "文件上传成功";
    }
}
